const koa = require('koa')
const router = require('koa-router')
const bodyParser = require('koa-bodyparser')
const mysql = require('mysql')
const app = new koa()
const route = new router()
const crypto = require('crypto');
const connection = mysql.createConnection({
    host     : 'localhost',
    user     : '1707b',
    password : '123456',
    database : '1707b' // 数据库的名字
})
connection.connect()
app.use(bodyParser()).use(route.routes()).use(route.allowedMethods())
app.use(async(ctx, next) => {
    await next()
    console.log(ctx.response.body)
})
// 注册
route.post('/api/register', async(ctx, next) => {
    try { 
        const {phone, password} = ctx.request.body
        const secret = password;
        const hash = crypto.createHmac('sha256', secret)
                        .update('I love cupcakes')
                        .digest('hex');
        // 注册
        // 第一步：检查数据库中是否有该用户（手机号）
        // 按手机号来查找，看是否有数据返回
        const arr = await new Promise((resolve, reject) => {
            connection.query('select * from user where phone=?', phone ,function(err, result) {
                if (err) {
                    reject(err)
                } else {
                    resolve(result)
                }
            })
        })
        if(arr.length === 0) { // 说明是一个新用户，要进行数据库的插入
            await new Promise((resolve, reject) => {
                connection.query('insert into user set ?', { phone, password: hash },function(err, result) {
                    if(err) reject(err)
                    resolve(result)
                })
            })
            ctx.response.body = {
                code:1,
                msg: '注册成功'
            }
        } else {
            ctx.response.body = {
                code:0,
                msg: '该用户已存在'
            }
        }
    } catch(e){
        ctx.response.body = {
            code: 0,
            msg: e.message
        }
    }
})

route.post('/api/login', async(ctx, next) => {
    try {
        const { phone, password } = ctx.request.body
        const secret = password;
        const hash = crypto.createHmac('sha256', secret)
                        .update('I love cupcakes')
                        .digest('hex');
        
        const arr = await new Promise((resolve, reject) => {
            // connection.query(`select * from user where phone="${phone}" and password="${hash}"`, (err, result) => {
            connection.query(`select * from user where phone=? and password=?`, [phone, hash], (err, result) => {
                if (err) reject(err)
                resolve(result)
            })
        })
        if (arr.length === 1) {
            ctx.response.body = {
                code: 1,
                signinnum: arr[0].signinnum,
                msg: '登录成功'
            }
        } else {
            ctx.response.body = {
                code: 0,
                msg: '查无此人'
            }
        }

    }catch(e) {
        ctx.response.body = {
            code: 0,
            msg: e.message
        }
    }
})


route.post('/api/signin', async(ctx, next) => {
    try {
        const { phone } = ctx.request.body
        const nowTime = new Date().toLocaleDateString()
        // 第一种方案
        // const userData = await new Promise((resolve, reject) => {
        //     connection.query('select * from user where phone=?', phone, (err, result) => {
        //         if (err) reject(err)
        //         resolve(result)
        //     })
        // })
        // if (userData.length > 0) { // 今天已签到了
        //     if (userData[0].signindate === nowTime) {
        //         ctx.response.body = {
        //             code: 0,
        //             msg: '今天已签到了'
        //         }
        //     } else {
        //         await new Promise((resolve, reject) => {
        //             connection.query('update user set signinnum=?, signindate=? where phone=?', [userData[0].signinnum+1, nowTime, phone],(err, result) => {
        //                 if(err) reject(err)
        //                 resolve(result)
        //             })
        //         })
        //         ctx.response.body = {
        //             code: 1,
        //             signinnum: userData[0].signinnum+1,
        //             msg: '签到成功'
        //         }
        //     }
            
        // } else {
        //     ctx.response.body = {
        //         code: 0,
        //         msg: '查无此人，不能签到'
        //     }
        // }
        // 第二种方案

        // 去签到表查询今天是否已签到
        const arr = await new Promise((resolve, reject) => {
            connection.query('select * from signin where phone=? and date=?', [phone, nowTime],(err, result) => {
                if(err) reject(err)
                resolve(result)
            })
        })
        console.log(arr)
        if (arr.length === 1) { // 今天已经签到了
            ctx.response.body = {
                code: 0,
                msg: '今天已签到'
            }
        } else { // 今天没有签到过
            await new Promise((resolve, reject) =>{
                connection.query('insert into signin set ?', {
                    phone,date: nowTime
                }, (err, result) => {
                    if (err) reject(err)
                    resolve(result)
                })
            })
            ctx.response.body = {
                code: 1,
                msg: '签到成功'
            }
        }
    }catch(e) {
        ctx.response.body = {
            code: 0,
            msg: e.message
        }
    }
})


app.listen(3000)